package com.nbjtjc.safe.service.report;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.cost.*;
import com.nbjtjc.safe.mapper.sys.SysDeptMapper;
import com.nbjtjc.safe.model.cost.*;
import com.nbjtjc.safe.util.FileUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@Service
public class CostReportService {
	@Autowired
	  private CostInjuryClaimMapper costInjuryClaimMapper;
	@Autowired
	  private CostInjuryClaimRecordMapper costInjuryClaimRecordMapper;
	
	@Autowired
	  private CostBudgetPlanMapper costBudgetPlanMapper;
	@Autowired
	  private CostBudgetItemMapper costBudgetItemMapper;
	@Autowired
	  private CostBudgetSubItemMapper costBudgetSubItemMapper;
	@Autowired
	private SysDeptMapper sysDeptMapper;
	
	@Autowired
	  private CostAccountRegMapper costAccountRegMapper;
	@Autowired
	  private CostAccountRecordMapper costAccountRecordMapper;
	
    //TODO 临时文件的清理
    @Value("${file.path.tempPath}")
    private String fileTempPath;
    @Autowired
    private FileUtil fileUtil;
    
    //员工受伤获赔台账
    public Result costInjuryClaimExcel(HttpServletResponse response,Date year){

        	Result result = new Result();
        	int claimId=-1;    	 
    	try {
    		
        	//根据年份找出获赔记录主表ID
        	CostInjuryClaim costInjuryClaimSample = new CostInjuryClaim();
        	costInjuryClaimSample.setYear(year);
        	costInjuryClaimSample.setCompanyId(MyShiroUtils.getCompanyId());

        	List<CostInjuryClaim> costInjuryClaims = costInjuryClaimMapper.search(costInjuryClaimSample);
        	if(CollectionUtil.isEmpty(costInjuryClaims)){
//        		result.setFalse("该年份员工获赔记录为空");
        		return result;
        	}else if(costInjuryClaims.size()>1){
        		result.setFalse("该年份员工获赔记录有多个，请检查");
        		return result;
        	}else{
        		claimId = costInjuryClaims.get(0).getId();
        	}
        	Map <String,Object> map = new HashMap();
        	CostInjuryClaim costInjuryClaim = costInjuryClaimMapper.show(claimId);
        	if(ObjectUtil.isNull(costInjuryClaim)){
        		return result;
        	}
        	if(CollectionUtil.isEmpty(costInjuryClaim.getCostInjuryClaimRecords())){
            	map.put("costRecords", new ArrayList());
        	}else{
            	List<CostInjuryClaimRecord> records=costInjuryClaim.getCostInjuryClaimRecords();
            	int i  = 1;
            	for(CostInjuryClaimRecord record:records){
//            		record.setId(i);
            		record.setNum(i);
            		records.set(i-1, record);
            		i++;
            	}
            	map.put("costRecords", records); 
        	}
        	
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/cost/costInjuryClaim.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(4);
            
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            
            String filePath = fileTempPath + "受伤员工获赔记录表" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();

            fileUtil.writeFile(response, new File(filePath));
            
    	}catch(IOException e) {
            e.printStackTrace();
    	}
    	return result;
    }
    
    //预算计划台账
    public Result costBudgetPlanExcel(HttpServletResponse response,Date year){
    	Result result = new Result();
    	int planId=-1;   
    	
    	try {
        	//根据年份找出预算计划主表ID
    		CostBudgetPlan costBudgetPlanSample = new CostBudgetPlan();
    		costBudgetPlanSample.setYear(year);
    		costBudgetPlanSample.setDeptId(MyShiroUtils.getCompanyId());
        	List<CostBudgetPlan> costBudgetPlans = costBudgetPlanMapper.search(costBudgetPlanSample);
        	if(CollectionUtil.isEmpty(costBudgetPlans)){
//        		result.setFalse("该预算计划记录为空");
        		return result;
        	}else if(costBudgetPlans.size()>1){
        		result.setFalse("该预算计划记录有多个，请检查");
        		return result;
        	}else{
        		planId = costBudgetPlans.get(0).getId();
        	}
    		
    		
    		
        	Map <String,Object> map = new HashMap();

        	CostBudgetPlan costBudgetPlan = costBudgetPlanMapper.show(planId);
        	if(ObjectUtil.isNull(costBudgetPlan)){
        		return result;
        	}
        	List<CostBudgetItem> costBudgetItems = costBudgetPlan.getCostBudgetItems();
        	
        	
        	if(CollectionUtil.isEmpty(costBudgetItems)){
        		map.put("items", new ArrayList());
        	}else{
        	
	        	Integer i = 1;
	        	
	        	//对每个项目，获取排序num和子项目数据
	        	for(CostBudgetItem costBudgetItem:costBudgetItems){
	        		costBudgetItem = costBudgetItemMapper.show(costBudgetItem.getId());
	        		costBudgetItem.setNum(i);
	        		costBudgetItems.set(i-1, costBudgetItem);
	        		i++;
	        	}
	        	//items存储最终预算计划结果，包括项目和子项目
	        	List<CostBudgetSubItem> items = new ArrayList();
	        	//临时subItem对象，将项目内容存到子项目对象中的临时变量
	        	List<CostBudgetSubItem> tempSubItem = new ArrayList();
	        	
	        	Integer n=0;
	        	for(CostBudgetItem costBudgetItem:costBudgetItems){
	        		List<CostBudgetSubItem> subItems = costBudgetItem.getCostBudgetSubItems();
	        		tempSubItem.add(new CostBudgetSubItem());
	        		//将项目的内容存到一个subitem对象中，以便存到items中
	        		tempSubItem.get(n).setItem(costBudgetItem.getItem());
	        		tempSubItem.get(n).setItemBudget(costBudgetItem.getItemTotalBudget());
	        		tempSubItem.get(n).setRemark(costBudgetItem.getRemark());
	        		//将序号转为String存在SortField中
		        	tempSubItem.get(n).setSortField(""+costBudgetItem.getNum());

	        		//将金额转为String存在SortOrder中
	        		tempSubItem.get(n).setSortOrder(""+costBudgetItem.getItemTotalBudget());
	        		
	        		//将内容加入items
	        		items.add(tempSubItem.get(n));
	        		n++;
	        		
	        		if(CollectionUtil.isNotEmpty(subItems)){
	        			i=1;
	        			for(CostBudgetSubItem subItem:subItems){
	        				//将序号转为String存在SortField中,格式为【项目序号.子项目序号】，例如：1.1、1.2
	        				subItem.setSortField(costBudgetItem.getNum()+"."+i);
	        				i++;
	        				//将金额转为String存在SortOrder中
	        				subItem.setSortOrder("    "+subItem.getItemBudget());
	        				//将内容加入items
	        				items.add(subItem);
	        				
		        		}
	        		}
	        	}
	        	map.put("items", items);
	        	map.put("title", costBudgetPlan.getTitle());
	            map.put("deptName", sysDeptMapper.findNameById(MyShiroUtils.getDeptId()));
        	}
        	
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/cost/costBudgetPlan.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(4);
            
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            
            String filePath = fileTempPath + "安全生产投入预算计划表" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
            
    	}catch(IOException e) {
            e.printStackTrace();
    	}
    	return result;
    }
    
    //预算投入台账
    public Result costAccountRecExcel(HttpServletResponse response,Date year){
    	Result result = new Result();
    	int regId=-1; 
    	
    	try {
        	//根据年份找出预算投入主表ID
    		CostAccountReg costAccountRegSample = new CostAccountReg();
    		costAccountRegSample.setYear(year);
    		costAccountRegSample.setCompanyId(MyShiroUtils.getCompanyId());

        	List<CostAccountReg> costAccountRegs = costAccountRegMapper.search(costAccountRegSample);
        	if(CollectionUtil.isEmpty(costAccountRegs)){
        		result.setFalse("该预算投入记录为空");
        		return result;
        	}else if(costAccountRegs.size()>1){
        		result.setFalse("该预算投入记录有多个，请检查");
        		return result;
        	}else{
        		regId = costAccountRegs.get(0).getId();
        	}
    		
    		
    		
        	Map <String,Object> map = new HashMap();
        	CostAccountReg costAccountReg = costAccountRegMapper.show(regId);
        	if(ObjectUtil.isNull(costAccountReg)){
        		return result;
        	}
        	if(CollectionUtil.isEmpty(costAccountReg.getCostAccountRecords())){
            	map.put("costAccounts", new ArrayList());
        	}else{
            	List<CostAccountRecord> records=costAccountReg.getCostAccountRecords();
            	Integer i  = 1;
            	for(CostAccountRecord record:records){
            		records.get(i-1).setNum(i);
            		i++;
            	}
            	map.put("costAccounts", records); 
            	map.put("title", costAccountReg.getTitle());
        	}
        	
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/cost/costAccountRec.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(4);
            
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            
            String filePath = fileTempPath + "安全生产费用投入登记表" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
            
    	}catch(IOException e) {
            e.printStackTrace();
    	}
		return result;
    }
    
    
    //预算执行台账
    public Result costBudgetImplExcel(HttpServletResponse response,Date year){
    	Result result = new Result();
    	int planId=-1;  
    	
    	
    	try {
       	//根据年份找出预算计划主表ID
    		CostBudgetPlan costBudgetPlanSample = new CostBudgetPlan();
    		costBudgetPlanSample.setYear(year);
    		costBudgetPlanSample.setDeptId(MyShiroUtils.getCompanyId());
        	List<CostBudgetPlan> costBudgetPlans = costBudgetPlanMapper.search(costBudgetPlanSample);
        	if(CollectionUtil.isEmpty(costBudgetPlans)){
        		result.setFalse("该预算计划记录为空");
        		return result;
        	}else if(costBudgetPlans.size()>1){
        		result.setFalse("该预算计划记录有多个，请检查");
        		return result;
        	}else{
        		planId = costBudgetPlans.get(0).getId();
        	}
    		
    		
    		
        	Map <String,Object> map = new HashMap();

        	CostBudgetPlan costBudgetPlan = costBudgetPlanMapper.show(planId);
        	if(ObjectUtil.isNull(costBudgetPlan)){
        		return result;
        	}
        	List<CostBudgetItem> costBudgetItems = costBudgetPlan.getCostBudgetItems();
        	
        	
        	if(CollectionUtil.isEmpty(costBudgetItems)){
        		map.put("items", new ArrayList());
        	}else{
        	
	        	Integer i = 1;
	        	
	        	//对每个项目，获取排序num和子项目数据
	        	for(CostBudgetItem costBudgetItem:costBudgetItems){
	        		costBudgetItem = costBudgetItemMapper.show(costBudgetItem.getId());
	        		costBudgetItem.setNum(i);
	        		costBudgetItems.set(i-1, costBudgetItem);
	        		i++;
	        	}
	        	//items存储最终预算计划结果，包括项目和子项目
	        	List<CostBudgetSubItem> items = new ArrayList();
	        	//临时subItem对象，将项目内容存到子项目对象中的临时变量
	        	List<CostBudgetSubItem> tempSubItem = new ArrayList();
	        	
	        	Integer n=0;
	        	for(CostBudgetItem costBudgetItem:costBudgetItems){
	        		List<CostBudgetSubItem> subItems = costBudgetItem.getCostBudgetSubItems();
	        		tempSubItem.add(new CostBudgetSubItem());
	        		//将项目的内容存到一个subitem对象中，以便存到items中
	        		tempSubItem.get(n).setItem(costBudgetItem.getItem());
	        		if(ObjectUtil.isNull(costBudgetItem.getItemTotalBudget())){
	        			costBudgetItem.setItemTotalBudget((float) 0);
	        		}
	        		if(ObjectUtil.isNull(costBudgetItem.getAccountSum())){
	        			costBudgetItem.setAccountSum((float) 0);
	        		}
	        		tempSubItem.get(n).setItemBudget(costBudgetItem.getItemTotalBudget());
	        		tempSubItem.get(n).setAccountSum(costBudgetItem.getAccountSum());
	        		tempSubItem.get(n).setAccountRemain(costBudgetItem.getItemTotalBudget()-costBudgetItem.getAccountSum());

	        		//将序号转为String存在SortField中
		        	tempSubItem.get(n).setSortField(""+costBudgetItem.getNum());

//	        		//将金额转为String存在SortOrder中
//	        		tempSubItem.get(n).setSortOrder(""+costBudgetItem.getItemTotalBudget());
	        		
	        		//将内容加入items
	        		items.add(tempSubItem.get(n));
	        		n++;
	        		
	        		if(CollectionUtil.isNotEmpty(subItems)){
	        			i=1;
	        			for(CostBudgetSubItem subItem:subItems){
	        				//将序号转为String存在SortField中,格式为【项目序号.子项目序号】，例如：1.1、1.2
	        				subItem.setSortField(costBudgetItem.getNum()+"."+i);
	        				subItem.setAccountRemain(subItem.getItemBudget()-subItem.getAccountSum());
	        				i++;
//	        				//将金额转为String存在SortOrder中
//	        				subItem.setSortOrder("    "+subItem.getItemBudget());
	        				//将内容加入items
	        				items.add(subItem);
	        				
		        		}
	        		}
	        	}
	        	map.put("items", items);
	        	map.put("title", costBudgetPlan.getTitle());
	            map.put("deptName", sysDeptMapper.findNameById(MyShiroUtils.getDeptId()));
        	}
        	
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/cost/costBudgetImpl.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(4);
            
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            
            String filePath = fileTempPath + "安全生产投入预算执行情况表" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
            
    	}catch(IOException e) {
            e.printStackTrace();
    	}
    	return result;
    }
}
